<?
if (!defined('SMF'))
	die('Hacking attempt...');

global $fighter_price;

$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_universe}
	WHERE sector_id = {int:sector_id}',
	array(
		'db_universe' => $dbtables['universe'],
		'sector_id' => $sector
	)
);

//Put the sector information into the array "sectorinfo"
$sectorinfo = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);

$result = $smcFunc['db_query']('', '
	SELECT *
	FROM {raw:db_sector_defence}
	WHERE sector_id = {int:sector_id}
	AND defence_type ="F"
	ORDER BY quantity DESC',
	array(
		'db_sector_defence' => $dbtables['sector_defence'],
		'sector_id' => $sector
	)
);
//Put the defence information into the array "defenceinfo"
$i = 0;
$total_sector_fighters = 0;
$owner = TRUE;
	
if ($smcFunc['db_num_rows']($result) > 0)
{
	while ($defences[$i]= $smcFunc['db_fetch_assoc']($result))
	{
		$total_sector_fighters += $defences[$i]['quantity'];
		if ($defences[$i]['ship_id'] != $playerinfo['ship_id'])
			$owner = false;
		$i++;
	}
}
$smcFunc['db_free_result']($result);

$num_defences = $i;
    
if ($num_defences > 0 && $total_sector_fighters > 0 && !$owner)
{
	// Find out if the fighter owner and player are on the same team.
	// All sector defences must be owned by members of the same team.
	$fm_owner = $defences[0]['ship_id'];
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE ship_id = {int:fm_owner}',
		array(
			'db_ships' => $dbtables['ships'],
			'fm_owner' => $fm_owner
		)
	);
	$fighters_owner = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	if ($fighters_owner['team'] != $playerinfo['team'] || $playerinfo['team'] == 0)
	{
		// Get POST variables.
		if (isset($_POST['response']))
			$response = $_POST['response'];
		elseif (isset($_GET['response']))
			$response = $_GET['response'];
		else
			$response = '';
		
		// Run actions depending on the players response to fighters in the sector.
		if ($response == "fight")
		{
			$result = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET cleared_defences = NULL
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
			echo '
						<input id="status" type="hidden" value="fighters" />';
						
			include("sector_fighters.php");
		}
		elseif ($response == "retreat")
		{
			$result = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET cleared_defences = NULL
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
			
			$result = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET last_login = NOW(), 
					turns = turns - 2, 
					turns_used = turns_used + 2, 
					sector = {int:sector_id}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'sector_id' => $playerinfo['sector'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
				
			$result = $smcFunc['db_query']('', '
				SELECT turns, turns_used
				FROM {raw:db_ships}
				WHERE user_id = {int:user_id}
				LIMIT 1',
				array(
					'db_ships' => $dbtables['ships'],
					'user_id' => $user_info['id'],
				)
			);
			$moveresult = $smcFunc['db_fetch_assoc']($result);
			$smcFunc['db_free_result']($result);
			
			$ok = 0;
			
			$txt['bnt_chf_youretreatback'] = str_replace("[sector]", $sector, $txt['bnt_chf_youretreatback']);
			$txt['bnt_rs_turns'] = str_replace("[triptime]", '<strong>2</strong>', $txt['bnt_rs_turns']);
			
			echo '
						<input id="status" type="hidden" value="retreat" />
						', $txt['bnt_chf_youretreatback'], '<br />
						', $txt['bnt_rs_turns'];
		}
		elseif ($response == "pay")
		{
			$result = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET cleared_defences = NULL
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
			
			$fighterstoll = $total_sector_fighters * $fighter_price * 0.6;
			
			if ($playerinfo['credits'] < $fighterstoll)
			{
				echo $txt['bnt_chf_notenoughcreditstoll'], '<br><br>';
				echo $txt['bnt_chf_youretreatback'], '<br><br>';
				// undo the move
				$result = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET sector = {int:sector_id}
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'sector_id' => $playerinfo['sector'],
						'ship_id' => $playerinfo['ship_id']
					)
				);
				$ok = 0;
			}
			else
			{
				$tollstring = NUMBER($fighterstoll);
				
				$txt['bnt_chf_youpaidsometoll'] = str_replace("[chf_tollstring]", $tollstring, $txt['bnt_chf_youpaidsometoll']);
				echo $txt['bnt_chf_youpaidsometoll'], '<br>';
				
				$result = $smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET credits = credits - {int:fighterstoll}
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'fighterstoll' => $fighterstoll,
						'ship_id' => $playerinfo['ship_id']
					)
				);
				
				distribute_toll($sector, $fighterstoll, $total_sector_fighters);
				playerlog($playerinfo['ship_id'], LOG_TOLL_PAID, "$tollstring|$sector");
				
				$ok = 1;
			}
		}
		elseif ($response == "sneak")
		{
			$result = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET cleared_defences = NULL
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id']
				)
			);
			
			$success = SCAN_SUCCESS($fighters_owner['sensors'], $playerinfo['cloak']);
			
			if ($success < 5)
				$success = 5;
			if ($success > 95)
				$success = 95;
				
			$roll = rand(1, 100);
			
			if ($roll < $success)
			{
				// Sector defences detect incoming ship
				echo '
						<input id="status" type="hidden" value="fighters" />
						', $txt['bnt_chf_thefightersdetectyou'], '<br />';
						
				include("sector_fighters.php");
			}
			else
			{
			   // sector defences don't detect incoming ship
			   $ok = 1;
			}
		}
		else
		{
			$ok = 0;
			
			// Get any available query string or POST variables and build the interface string
			if (isset($_POST['sector']))
				$sector = $_POST['sector'];
			
			$interface_string = 'sa=' . $calledfrom . ';sector=' . $sector;
			
			if (isset($_POST['destination']))
			{
				$destination = $_POST['destination'];
				$interface_string .= ';destination=' . $destination;
			}
			elseif (isset($destination))
				$interface_string .= ';destination=' . $destination;
			else
				$destination = '';
			
			if (isset($_POST['engage']))
			{
				$engage = $_POST['engage'];
				$interface_string .= ';engage=' . $engage;
			}
			elseif (isset($engage))
				$interface_string .= ';engage=' . $engage;
			else
				$engage = '';	
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET cleared_defences = {string:interface_string}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'interface_string' => $interface_string,
					'ship_id' => $playerinfo['ship_id']
				)
			);
			
			$fighterstoll = $total_sector_fighters * $fighter_price * 0.6;
			
			echo '
						<input id="status" type="hidden" value="fighters" />
						<form id="cf_form" action="">';
			
			$txt['bnt_chf_therearetotalfightersindest'] = str_replace("[chf_total_sector_fighters]", NUMBER($total_sector_fighters), $txt['bnt_chf_therearetotalfightersindest']);
			$txt['bnt_chf_therearetotalfightersindest'] = str_replace("[sector]", $sector, $txt['bnt_chf_therearetotalfightersindest']);
			echo $txt['bnt_chf_therearetotalfightersindest'], '<br><br>';
			
			if ($defences[0]['fm_setting'] == "toll")
			{
				$txt['bnt_chf_creditsdemanded'] = str_replace("[chf_number_fighterstoll]", NUMBER($fighterstoll), $txt['bnt_chf_creditsdemanded']);
				echo $txt['bnt_chf_creditsdemanded'], '<br><br>';
			}
			
			echo $txt['bnt_chf_youcanretreat'];
			
			if ($defences[0]['fm_setting'] == "toll")
				echo $txt['bnt_chf_inputpay'];
				
			echo $txt['bnt_chf_inputfight'];
			echo $txt['bnt_chf_inputcloak'], '<br>';
			echo '<a id="cf_action" class="bnt_button" href="#">', $txt['bnt_chf_go'], '</a><br><br>';
			echo '<input type="hidden" id="cf_calledfrom" name="calledfrom" value="', $calledfrom, '">';
			echo '<input type="hidden" id="cf_sector" name="sector" value="', $sector, '">';
			echo '<input type="hidden" id="cf_engage" name="engage" value="1">';
			echo '<input type="hidden" id="cf_dest" name="destination" value="', $destination, '">';
			echo '</form>';
			return;
		}

		// Clean up any sectors that have used up all mines or fighters.
		$result = $smcFunc['db_query']('', '
			DELETE FROM {raw:db_sector_defence}
			WHERE quantity <= 0',
			array(
				'db_sector_defence' => $dbtables['sector_defence']
			)
		);
	}
}

?>
